package www.openteam.com.ui.business.other;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.adapter.ProAdapter;
import www.openteam.com.adapter.other.WOSearchAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.PeopleGroup;
import www.openteam.com.contract.business.other.WOSearchContract;
import www.openteam.com.presenter.business.other.WOSearchPresenter;
import www.openteam.com.tool.EditTextShakeTool;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by kylin on 2017/5/16.
 */

public class WOSearchFragment extends mBaseFragment<WOSearchPresenter>
        implements WOSearchContract.WOSearchView {

    private String TAG = WOSearchFragment.class.getSimpleName();
    private FragmentManager manager;
    private FragmentTransaction ft;
    @Bind(R.id.et_search)
    EditText et_search;
    @Bind(R.id.iv_search)
    ImageView iv_search;
    private int position;
    private ArrayList<PeopleGroup.DataEntity> peopleGroupList;
    private WOSearchAdapter woSearchAdapter;
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private ProAdapter produceScheduleAdapter = null;
    String failInfo;
    private int pageSize = 0;
    private ButtonSelect buttonSelect;
    private String machineCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        args.putInt("position", 2);
//        args.putString("mark", "查询班组");
        position = getArguments().getInt("position");
        machineCode = getArguments().getString("searchCondition");
        String mark = getArguments().getString("mark");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);

        view = inflater.inflate(getLayoutId(), container, false);
        manager = getFragmentManager();
        mPresenter = loadPresenter();
        initCommonData();
        initView();
        initListener();
        initData();

        return view;
    }


    private void initCommonData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        iv_search.setOnClickListener(this);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, view);
        et_search.setText(machineCode);

        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //关闭软键盘
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et_search.getWindowToken(), 0);
                    //使得根View重新获取焦点，以监听返回键

                    getFocus();
                    return true;
                }

                return false;
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_search:
                if (et_search.getText().toString().equals("")) {
                    ToastUtil.showToast(getContext(), "查詢條件不能為空");
                    new EditTextShakeTool(getContext()).shake(et_search);
                } else {
                    if (position == 1) {
                        if (produceScheduleAdapter == null) {
                            peopleGroupList = new ArrayList<PeopleGroup.DataEntity>();
                            mPresenter.findPeopleGroup(et_search.getText().toString(),
                                    pageSize);
                        } else {
                            mRecyclerView.removeAllViews();
                            failInfo = null;
                            i = 0;
                            peopleGroupList.clear();
                            Log.d(TAG, "onClick: " + peopleGroupList.size());
                            onRefresh();
                        }
                    } else if (position == 2) {
                        if (produceScheduleAdapter == null) {

                            peopleGroupList = new ArrayList<PeopleGroup.DataEntity>();
                            mPresenter.findBanzu(et_search.getText().toString(),
                                    pageSize);
                        } else {
                            mRecyclerView.removeAllViews();
                            failInfo = null;
                            i = 0;
                            peopleGroupList.clear();
                            onRefresh();
                        }
                    }
                }
                break;

        }
    }

    @Override
    protected WOSearchPresenter loadPresenter() {
        return new WOSearchPresenter();
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_search;
    }

    @Override
    public void onResume() {
        super.onResume();
        getFocus();
    }

    @Override
    public void onPause() {
        super.onPause();
        getFocus();

    }

    private void getFocus() {
        getView().setFocusable(true);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();

        getView().setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

//                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
//                    Log.d(TAG, "onKey: " + keyCode + ":"+event.getAction()+":"+":::::");
//                    ft = manager.beginTransaction();
//                    ft.remove(WOSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
//                    ft.commit();
//                    return true;// 未处理
//                }
//                return false;


                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            /*
             * 注意在if判断中要加一个event.getAction() == KeyEvent.ACTION_DOWN判断，
			 * 因为按键有两个事件ACTION_DOWN和ACTION_UP，也就是按下和松开，
			 * 如果不加这个判断，代码会执行两遍
			 */
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {
                        Log.d(TAG, "onKey: " + keyCode + "-:" + event.getAction() + ":" + ":::::");
                        ft = manager.beginTransaction();
                        ft.remove(WOSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
                        ft.commit();
                    }
                    return true;
                }
                return false;
            }
        });

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
//        menu.add(0, 1, 0, "return").setShowAsAction(
//                MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId()==android.R.id.home){
//            Log.d(TAG, "onOptionsItemSelected: +home");
//            getActivity().getFragmentManager().popBackStack();
//            return false;
//        }
        switch (item.getItemId()) {
            case 1://这个0是上图中“操作”字样的ItmeId
                ft = manager.beginTransaction();
                ft.remove(WOSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
                ft.commit();
                return true;
            case android.R.id.home:// 点击返回图标事件
                Log.d(TAG, "onOptionsItemSelected: activit");
                getActivity().getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void querySSuccess(PeopleGroup peopleGroup) {
        for (PeopleGroup.DataEntity dev : peopleGroup.getData()) {
            peopleGroupList.add(dev);
            Log.d(TAG, "querySSuccess: " + dev.getGroupcount());
        }
        setPeopleInfosAdapter();
    }

    @Override
    public void querySFail(String failMsg) {
        failInfo = failMsg;
        RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
        ToastUtil.showToast(getActivity(), failMsg);
    }

    @Override
    public void queryBSuccess(PeopleGroup banGroup) {
        for (PeopleGroup.DataEntity dev : banGroup.getData()) {
            peopleGroupList.add(dev);
//            Log.d(TAG, "queryBSuccess: "+dev.getRownumber());
        }
        setPeopleInfosAdapter();
    }

    @Override
    public void queryBFail(String failMsg) {
        failInfo = failMsg;
        RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
        ToastUtil.showToast(getActivity(), failMsg);
    }


    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!et_search.getText().toString().isEmpty())) {
            mRecyclerView.removeAllViews();
            peopleGroupList.clear();
            woSearchAdapter = null;
            mFooterRecyclerViewAapter = null;
            switch (position) {
                case 1:
                    mPresenter.findPeopleGroup(et_search.getText().toString(), 0);
//                    getMoreCom(),getUserId(),getJMark(),
                    break;
                case 2:
                    mPresenter.findBanzu(et_search.getText().toString(), 0);
                    break;
            }
            failInfo = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!et_search.getText().toString().isEmpty())) {
            mRecyclerView.removeAllViews();
            produceScheduleAdapter = null;
            mFooterRecyclerViewAapter = null;
            switch (position) {
                case 1:
                    mPresenter.findPeopleGroup(et_search.getText().toString(), 0);
//                    getMoreCom(),getUserId(),getJMark(),
                    break;
                case 2:
                    mPresenter.findBanzu(et_search.getText().toString(), 0);
                    break;
            }
            mSwipeRefresh.setRefreshing(false);
        }
    }

    public void initRView(View view) {

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_search);

        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                i++;
            }
            i++;
            if (failInfo == null && (peopleGroupList.size() % 10 == 0)) {

                Log.d(TAG, "onLoadNextPage: jx");
                peopleGroupList = new ArrayList<PeopleGroup.DataEntity>();
                switch (position) {
                    case 1:
                        mPresenter.findPeopleGroup(et_search.getText().toString(), i);
//                    getMoreCom(),getUserId(),getJMark(),
                        break;
                    case 2:
                        mPresenter.findBanzu(et_search.getText().toString(), i);
                        break;
                }

                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (failInfo == null && (peopleGroupList.size() % 10 != 0)) {
                //the end
                switch (position) {
                    case 1:
                        mPresenter.findPeopleGroup(et_search.getText().toString(), i);
//                    getMoreCom(),getUserId(),getJMark(),
                        break;
                    case 2:
                        mPresenter.findBanzu(et_search.getText().toString(), i);
                        break;
                }
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                failInfo = null;
            } else if (failInfo != null) {
                //the end
                i = 0;
                if (failInfo.toString().equals("com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 42 path $.data")) {
                    Log.d(TAG, "onLoadNextPage:  bunull ");
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                    failInfo = null;
                }
            }

        }
    };

    private void setPeopleInfosAdapter() {
        if (woSearchAdapter == null) {
            woSearchAdapter = new WOSearchAdapter(getActivity());
            woSearchAdapter.addItems(peopleGroupList);
            woSearchAdapter.addContext(getActivity());
            woSearchAdapter.cButtonSetOnclick(new WOSearchAdapter.CButtonTouchEvent() {
                @Override
                public void doubleClickSelect(PeopleGroup.DataEntity peoleGroup) {
                    buttonSelect.buttonOnclickSelect(peoleGroup, position);
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(woSearchAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");

            mFooterRecyclerViewAapter.notifyDataSetChanged();
            woSearchAdapter.addItems(peopleGroupList);
            woSearchAdapter.addContext(getActivity());
            woSearchAdapter.cButtonSetOnclick(new WOSearchAdapter.CButtonTouchEvent() {
                @Override
                public void doubleClickSelect(PeopleGroup.DataEntity peoleGroup) {
                    buttonSelect.buttonOnclickSelect(peoleGroup, position);
                }
            });
            ;
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.findPeopleGroup(et_search.getText().toString(), i);
        }
    };


    public interface ButtonSelect {

        void buttonOnclickSelect(PeopleGroup.DataEntity peopleGroup, int position);

    }


    public void buttonSetOnclick(ButtonSelect buttonSelect) {
        this.buttonSelect = buttonSelect;
    }


}
